import "./reset.css";
import { handleTree } from "@/utils/allAppTree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { deviceDetection } from "@pureadmin/utils";
import { type Ref, h, ref, computed, reactive, onMounted, watch } from "vue";
import { saveServiceInfo, changeApiStatus, removeApi } from "@/api/service";
import { callApiEventEmitter, pubApiEventEmitter } from "@/utils/eventBus";
import {
  getAppTreeList,
  getServiceList,
  subjectApi,
  unSubjectApi
} from "@/api/serviceMarks";
import { getAccount } from "@/utils/auth";
import { ResultCommon, serviceType } from "@/utils/commonType";

export function useCallAPI() {
  const form = reactive({
    // 左侧id
    pid: "",
    selectAppId: "root",
    username: "",
    phone: "",
    status: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref();
  const selectedAppId = ref("");

  const paginationForCard = ref({
    page: 1,
    pageSize: 12,
    total: 0,
    curApp: ""
  });
  const apiInfoList = ref([]);
  const dataLoading = ref(true);

  const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

  const INITIAL_DATA = {
    pid: "",
    serviceName: "",
    serviceDesc: "",
    appId: "",
    tenantId: "",
    serviceUrl: "",
    serviceDocId: "",
    publishClientId: "",
    lineStatus: "on",
    subject: false,
    status: false
  };

  const getCardListData = async (appId?: string, type?: string) => {
    if (appId === "root") {
      appId = "";
    }

    await getServiceList(getAccount().accountName, appId, type)
      .then(function (data) {
        apiInfoList.value = data.data;
        paginationForCard.value = {
          ...paginationForCard.value,
          total: data.data.length
        };
      })
      .catch(function (err) {
        message(`加载服务清单失败：${err.message}`, {
          type: "error"
        });
      });
    selectedAppId.value = appId;
    dataLoading.value = false;
  };

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const subjectService = async (service: serviceType, optType: boolean) => {
    const curAccount = getAccount().accountName;
    const serviceName = service.serviceName;
    let result: ResultCommon<boolean> = {
      code: -1,
      data: false,
      message: ""
    };
    if (optType) {
      subjectApi({ serviceId: service.pid, account: curAccount })
        .then(data => {
          if (data.data) {
            message(`成功订阅服务[${serviceName}]`, {
              type: "success"
            });
            callApiEventEmitter.emit("clickServiceCard", { pid: "" });
          }
        })
        .catch(err => {
          message(`订阅服务[${serviceName}]异常：${err.message}`, {
            type: "error"
          });
        });
    } else {
      unSubjectApi(service.pid, curAccount)
        .then(data => {
          if (data.data) {
            message(`成功取消订阅服务[${serviceName}]`, {
              type: "success"
            });
            callApiEventEmitter.emit("clickServiceCard", { pid: "" });
          }
        })
        .catch(err => {
          message(`取消订阅服务[${serviceName}]异常：${err.message}`, {
            type: "error"
          });
        });
    }
    return result;
  };

  const initData = async () => {
    getAppTreeList()
      .then(data => {
        higherDeptOptions.value = handleTree(data.data);
        treeData.value = handleTree(data.data);
      })
      .catch(err => {
        message(`获取应用清单异常：${err.message}`, {
          type: "error"
        });
      });
  };

  const onAddServiceInfo = async (service: serviceType) => {
    await saveServiceInfo(service);
  };
  function onChangeAPILine(service: serviceType, status: boolean) {
    ElMessageBox.confirm(
      `确认要${
        status ? "上线" : "下线"
      }<strong>${service.serviceName}</strong>服务吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        changeApiStatus(service.pid, status)
          .then(function (data) {
            message(
              `${status ? "上线" : "下线"}【${service.serviceName}】服务成功`,
              {
                type: "success"
              }
            );
            try {
              pubApiEventEmitter.emit("clickAppTreeNode", { pid: "root" });
            } catch (err) {
              message(
                `${status ? "上线" : "下线"}【${service.serviceName}】服务失败：${err.message}`,
                {
                  type: "error"
                }
              );
            }
          })
          .catch(function (err) {
            message(`刷新信息异常：${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {});
  }

  function onDeleteAPI(service: serviceType) {
    ElMessageBox.confirm(
      `确认要删除<strong>${service.serviceName}</strong>服务吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        removeApi(service.pid)
          .then(function (data) {
            message(`删除【${service.serviceName}】服务成功`, {
              type: "success"
            });
            try {
              pubApiEventEmitter.emit("clickAppTreeNode", { pid: "root" });
            } catch (err) {
              message(`刷新信息异常：${err.message}`, {
                type: "error"
              });
            }
          })
          .catch(err => {
            message(
              `删除<strong>${service.serviceName}</strong>服务异常：${err.message}`,
              {
                type: "error"
              }
            );
          });
      })
      .catch(err => {});
  }
  function handleSizeChange(val: number) {
    paginationForCard.value.pageSize = val;
    paginationForCard.value.page = 1;
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    paginationForCard.value.page = val;
  }

  return {
    form,
    loading,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    paginationForCard,
    apiInfoList,
    onChangeAPILine,
    onDeleteAPI,
    dataLoading,
    buttonClass,
    deviceDetection,
    handleSizeChange,
    handleCurrentChange,
    higherDeptOptions,
    handleTree,
    getCardListData,
    INITIAL_DATA,
    svg,
    selectedAppId,
    onAddServiceInfo,
    initData,
    subjectService
  };
}
